//
//  PhotoBrowserViewController.swift
//  WBDemo
//
//  Created by Meng on 17/2/17.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {

    
    var bmiddle_urls: [URL]?
    var indexPath: IndexPath?
    
    @IBOutlet weak var collectionView: UICollectionView!
    
//    init(bmiddle_urls: [URL], indexPath: IndexPath) {
//        self.bmiddle_urls = bmiddle_urls
//        self.indexPath = indexPath
//        // 注意: 自定义构造方法时候不一定是调用super.init(), 需要调用当前类设计构造方法(designated)
//        super.init(nibName: nil, bundle: nil)
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        collectionView.scrollsToTop = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func closeAction(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func saveAction(_ sender: UIButton) {
        let cell = collectionView.visibleCells.first as! BrowserCell
        let image = cell.imageView.image!
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    func image(image: UIImage, didFinishSavingWithError error:NSError?, contextInfo: AnyObject?) {
        if error != nil  {
            SVProgressHUD.showError(withStatus: "保存失败")
        } else {
            SVProgressHUD.showSuccess(withStatus: "保存成功")
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        guard let index = indexPath else {
            return
        }
        collectionView.scrollToItem(at: index, at: UICollectionViewScrollPosition.init(rawValue: 0), animated: false)
    }

}

extension PhotoBrowserViewController: UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bmiddle_urls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "browserCell", for: indexPath) as! BrowserCell
        
        cell.imageUrl = bmiddle_urls![indexPath.item]
        
        return cell
    }
}

class BrowserCell: UICollectionViewCell, UIScrollViewDelegate {
    
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    var imageUrl: URL? {
        didSet {
            
            // 显示菊花提醒
            indicatorView.startAnimating()
            
            resetView()
            
            imageView.sd_setImage(with: imageUrl) { (img: UIImage?, err: Error?, type: SDImageCacheType, url: URL?) in
                
                self.indicatorView.stopAnimating()
                
                let width = UIScreen.main.bounds.size.width
                let height = UIScreen.main.bounds.size.height
                let scale = img!.size.height / img!.size.width
                let imgHeight = scale * width
                
                self.imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: imgHeight))
                
                if imgHeight < height {
                    // 短图
                    // 4.计算顶部和底部内边距
                    let offsetY = (height - imgHeight) * 0.5
                    
                    // 5.设置内边距
                    self.scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
                } else {
                    self.scrollView.contentSize = CGSize(width: width, height: imgHeight)
                }
            }
        }
    }
    
    private func resetView() {
        scrollView.contentInset = UIEdgeInsets.zero
        scrollView.contentSize = CGSize.zero
        imageView.transform = CGAffineTransform.identity
    }
    
    lazy var imageView: UIImageView = UIImageView()
    /// 提示视图
    private lazy var indicatorView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    override func awakeFromNib() {
        super.awakeFromNib()
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        scrollView.addSubview(imageView)
        contentView.addSubview(indicatorView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        indicatorView.center = contentView.center
    }
    
    // MARK: - UIScrollViewDelegate
    // 告诉系统哪个view要进行缩放
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    // 每次缩放都会调用该方法
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        // frame == contentSize
        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height
        var offsetX = (width - imageView.frame.width) * 0.5
        var offsetY = (height - imageView.frame.height) * 0.5
        offsetX = (offsetX < 0) ? 0 : offsetX
        offsetY = (offsetY < 0) ? 0 : offsetY
        self.scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX)
    }
    
}

class BrowserLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        itemSize = UIScreen.main.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
